<template>
  <div class="st-box">

    <div class="search-bar" style="display: flex;width: 500px;padding-bottom: 10px;">
      <!-- 搜索输入框 -->
      <el-input v-model="name" style="width: 250px" placeholder="请学生姓名.."></el-input>
      <!-- 查询按钮 -->
      <el-button type="primary" @click="handleSearch" style="margin-left:10px">查询</el-button>
      <!-- 新增按钮 -->
      <el-button type="primary" @click="addStudent">新增学生</el-button>
      <el-button type="primary" @click="exportExcel">导出Excel</el-button>
    </div>

    <el-table
        :data="tableData"
        border
        style="width: 100%;font-size: 15px"
    >
      <el-table-column
          fixed
          prop="stuId"
          label="学生ID"
          width="80"
          align="center">
      </el-table-column>
      <el-table-column
          prop="name"
          label="姓名"
          width="80"
          align="center">
      </el-table-column>
      <el-table-column
          prop="stuNumber"
          label="学号"
          width="80"
          align="center">
      </el-table-column>
      <el-table-column
          prop="age"
          label="年龄"
          width="80"
          align="center">
      </el-table-column>
      <el-table-column
          prop="sex"
          label="性别"
          width="60"
          align="center">
      </el-table-column>
      <el-table-column
          prop="majorClass"
          label="班级"
          width="120"
          align="center">
      </el-table-column>
      <el-table-column
          prop="dormNumber"
          label="宿舍"
          width="80"
          align="center">
      </el-table-column>
      <el-table-column
          prop="stuDay"
          label="入学日期"
          width="100"
          align="center"
          dormId-format="yyyy-MM-dd">
      </el-table-column>
      <el-table-column
          prop="major"
          label="专业"
          width="150"
          align="center">
      </el-table-column>
      <el-table-column
          prop="stuPic"
          label="照片"
          width="120"
          align="center">
        <template slot-scope="scope">
          <img :src="scope.row.stuPic" alt="学生照片" style="width: 50px; height: 50px;">
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
              style="margin: 5px"
              type="primary">
            修改
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              style="margin: 5px">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 对话框 -->
    <el-dialog
        title="学生信息"
        :visible.sync="dialogVisible"
        width="500px"
        :before-close="closeDialog"
    >
      <!-- 表单内容 -->
      <el-form :model="formData" ref="form" label-width="50px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="stuNumber">
          <el-input v-model="formData.stuNumber"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="formData.age"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex" style="padding-right: 100px">
          <el-radio-group v-model="formData.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="班级" prop="majorClass">
          <el-input v-model="formData.majorClass"></el-input>
        </el-form-item>
        <!--宿舍多选-->
        <div style="padding-bottom: 20px;padding-right:180px;">
          <span style="padding-right: 10px;">宿舍{{key}}</span>
          <el-select style="padding-left: 0;" v-model="key" placeholder="请选择宿舍">
            <el-option
                v-for="item in options"
                :key="item.dormId"
                :label="item.dormNumber"
                :value="item.dormId">
            </el-option>
          </el-select>
        </div>

        <el-form-item label="入学日期" prop="stuDay" style="padding-right: 190px">
          <el-date-picker
              v-model="formData.stuDay"
              type="date"
              placeholder="选择日期"
              dormId-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="formData.major"></el-input>
        </el-form-item>

        <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            list-type="picture"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
        >
          <img style="width: 50px;height: 80px;margin: 0 10px -20px" v-if="formData.stuPic" :src="formData.stuPic"
               class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"
             style="size: 50px;color: #3BB201;padding-left: -100px"></i>
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>

      </el-form>

      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer" style="margin: auto">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>


    <!-- 分页组件，仅当有数据时显示 -->
    <div>
      <el-pagination
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          :current-page="currentPage"
          :page-sizes="[6, 10, 15, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {getStudent, addStudent, updateStudent, deleteStudent, getDormList,setDormDormId} from "@/api/api";
import XLSX from "xlsx";

export default {
  name: "StudentList",
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 6,
      total: 0,
      formData: {
        name: '',
        age: '',
        sex: '',
        major: '',
        stuPic: '' // 添加 stuPic 字段用于保存图片的 URL
      },
      dialogVisible: false,
      uploadUrl: 'http://localhost:8687/admin/common/upload',
      name: '',       // 新增 name 变量
      stuNumber: '',  // 新增 stuNumber 变量
      dormNumber: '',  // 新增 dormNumber 变量

      // 添加 options 变量用于保存宿舍信息
      options: [],
      key: '', // 添加 dormId 变量用于保存选中的宿舍信息
    };
  },
  created() {
    this.fetchData(this.currentPage, this.pageSize);
  },

  methods: {

    fetchData(page, size, name = '') {
      const params = {
        page: page,
        pageSize: size,
        name: name,
      };
      getStudent(params)
          .then(response => {
            if (response.data.code === 1) {
              this.tableData = response.data.data.records;
              this.total = response.data.data.total;
              console.log("获取学生成功")

            } else {
              console.error('获取学生数据时出错： ', response.data.msg);
            }
          })
          .catch(error => {
            console.error('获取学生数据时出错： ', error);
          });
    },
    // 分页
    handlePageChange(currentPage) {
      this.currentPage = currentPage;
      this.fetchData(currentPage, this.pageSize);
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData(this.currentPage, this.pageSize);
    },
    // 新增
    addStudent() {
      this.dialogVisible = true;
      this.getDormList()
    },
    // 编辑
    handleEdit(index, row) {
      this.formData = {...row};
      this.dialogVisible = true;
      this.getDormList()
    },
    // 处理删除图片事件
    handleRemove() {
      // 用户删除图片时，将表单数据中的图片 URL 清空
      this.formData.stuPic = '';
    },
    // 模糊查询
    // 处理搜索框输入事件
    handleSearch() {
      this.fetchData(this.currentPage, this.pageSize, this.name);

    },


    exportExcel() {
      // 准备导出的数据
      const data = this.tableData.map(item => ({
        '学生ID': item.stuId,
        '姓名': item.name,
        '学号': item.stuNumber,
        '年龄': item.age,
        '性别': item.sex,
        '班级': item.majorClass,
        '宿舍号': item.dormNumber,
        '入学日期': item.stuDay,
        '专业': item.major,
        '照片': item.stuPic
      }));

      // 创建一个工作簿
      const wb = XLSX.utils.book_new();

      // 将数据转换为工作表
      const ws = XLSX.utils.json_to_sheet(data);

      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      // 将工作簿转换为二进制数据
      const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'binary'});

      // 将二进制数据转换为 Blob 对象
      const blob = new Blob([s2ab(wbout)], {type: 'application/octet-stream'});

      // 创建下载链接并触发点击
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = '学生信息.xlsx';
      link.click();
    },
    // 关闭对话框
    closeDialog() {
      this.dialogVisible = false;
    },

    // 新增
    handleSubmit() {
      if (this.formData.stuId) {
        // 如果表单中存在学生ID，则执行更新操作
        updateStudent(this.formData)
            .then(response => {
              if (response.data.code === 1) {
                this.$message.success('更新成功');
                // 在这里调用 setDormDormId，并传递正确的参数
                setDormDormId(this.formData.stuId, this.key)
                    .then(() => {
                      this.fetchData(this.currentPage, this.pageSize);
                      this.closeDialog();
                    })
                    .catch(error => {
                      console.error('修改宿舍信息失败：', error);
                    });
              } else {
                this.$message.error(response.data.msg);
                console.log(response.data)
              }
            })
            .catch(error => {
              console.error('更新学生信息失败：', error);
            });
      } else {
        // 如果表单中不存在学生ID，则执行新增操作
        addStudent(this.formData)
            .then(response => {
              if (response.data.code === 1) {
                this.$message.success('新增成功');
                // 在这里调用 setDormDormId，并传递正确的参数
                setDormDormId(this.formData.stuId, this.key)
                    .then(() => {
                      this.fetchData(this.currentPage, this.pageSize);
                    })
                    .catch(error => {
                      console.error('修改宿舍信息失败：', error);
                    });
              } else {
                this.$message.error(response.data.msg);
              }
            })
            .catch(error => {
              console.error('新增学生信息失败：', error);
            });
      }
      this.closeDialog();
    },

    handleDelete(index, row) {
      this.$confirm('确认删除学生信息吗？删除后将无法恢复。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteStudent(row.stuNumber)
            .then(response => {
              if (response.data.code === 1) {
                this.$message.success('删除成功');
                this.fetchData(this.currentPage, this.pageSize);
              } else {
                this.$message.error(response.data.msg);
              }
            })
            .catch(error => {
              console.error('删除学生信息失败：', error);
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 图片上传
    // 处理上传成功事件
    handleUploadSuccess(response) {
      if (response.code === 1) {
        // 如果上传成功，将图片 URL 保存到表单数据中
        this.formData.stuPic = response.data;
        console.log(response.data)
        this.$message.success('图片上传成功');

        console.log(response.data.stuPic);
      } else {
        this.$message.error('图片上传失败：' + response.msg);
      }
    },
    getDormList() {
      // 获取多选的宿舍数据
      getDormList()
          .then(response => {
            if (response.data.code === 1) {
              this.options = response.data.data;

            } else {
              console.error('获取宿舍数据时出错： ', response.data.msg);
            }
          }).catch(error => {
        console.error('获取宿舍数据时出错： ', error);
      })
    }
  }
};

// 字符串转ArrayBuffer
function s2ab(s) {
  const buf = new ArrayBuffer(s.length);
  const view = new Uint8Array(buf);
  for (let i = 0; i < s.length; i++) {
    view[i] = s.charCodeAt(i) & 0xFF;
  }
  return buf;
}
</script>

<style>

</style>
